package com.admission.service;

import java.util.List;

import org.apache.commons.lang.xwork.StringUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.security.springsecurity.SpringSecurityUtils;

import com.admission.dao.AuthorityDao;
import com.admission.dao.RoleDao;
import com.admission.model.Authority;
import com.admission.model.Employee;
import com.admission.model.Role;

@Repository
@Transactional
public class RoleManager {
	private RoleDao roleDao;
	private AuthorityDao authorityDao;

	@Transactional(readOnly = true)
	public Role getRole(String id) {
		return roleDao.findUniqueBy("id", id);
	}

	@Transactional(readOnly = true)
	public List<Role> getAllRole() {
		Criterion criterions = Restrictions.ne("id", "1");
		return roleDao.find(criterions);
	}

	@Transactional(readOnly = true)
	public List<Authority> getAllAuthority() {
//		Criterion criterions = Restrictions.ne("id", "11");
//		Criterion criterions1 = Restrictions.ne("id", "13");
		return authorityDao.getAll();
	}

	public void saveRole(Role entity) throws Exception {
		if (isSupervisor(entity.getId())) {
			throw new Exception(SpringSecurityUtils.getCurrentUserName()
					+ "试图修改超级角色");
		}
		if (StringUtils.isEmpty(entity.getId())) {
			entity.setId(null);
		}
		roleDao.save(entity);
	}

	private boolean isSupervisor(String id) {
		return id.equals("1");
	}

	@Transactional
	public void deleteRole(String ids) throws Exception {
		for (String id : ids.split(",")) {
			if (isSupervisor(id)) {
				throw new Exception(SpringSecurityUtils.getCurrentUserName()
						+ "试图删除超级角色");
			}
			Role entity = roleDao.get(id);
			for (Employee e : entity.getEmployee()) {
				e.getRoles().remove(entity);
			}
			roleDao.delete(entity);
		}
	}

	@Autowired
	public void setRoleDao(RoleDao roleDao) {
		this.roleDao = roleDao;
	}

	@Autowired
	public void setAuthorityDao(AuthorityDao authorityDao) {
		this.authorityDao = authorityDao;
	}

}
